<template>
  <div class="page-container">
    <div class="page-header">
      <h2 class="page-title">配送订单</h2>
      <div class="header-actions">
        <el-button @click="refreshOrders" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
        <el-button 
          v-if="!isOnline" 
          type="success" 
          @click="goOnline"
        >
          上线接单
        </el-button>
        <el-button 
          v-else 
          type="warning" 
          @click="goOffline"
        >
          下线休息
        </el-button>
      </div>
    </div>

    <!-- 配送员状态 -->
    <el-card class="status-card mb-3">
      <div class="status-info">
        <div class="status-item">
          <span class="label">当前状态：</span>
          <el-tag :type="isOnline ? 'success' : 'info'" size="large">
            {{ isOnline ? '在线' : '离线' }}
          </el-tag>
        </div>
        <div class="status-item">
          <span class="label">今日配送：</span>
          <span class="value">{{ todayDeliveries }}单</span>
        </div>
        <div class="status-item">
          <span class="label">今日收入：</span>
          <span class="value">¥{{ todayEarnings }}</span>
        </div>
      </div>
    </el-card>

    <!-- 订单状态筛选 -->
    <el-card class="filter-card mb-3">
      <el-tabs v-model="activeStatus" @tab-change="handleStatusChange">
        <el-tab-pane label="待接单" name="READY"></el-tab-pane>
        <el-tab-pane label="配送中" name="DELIVERING"></el-tab-pane>
        <el-tab-pane label="已完成" name="COMPLETED"></el-tab-pane>
        <el-tab-pane label="全部" name=""></el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 订单列表 -->
    <div class="orders-container">
      <el-card v-for="order in orders" :key="order.id" class="order-card mb-3">
        <!-- 订单头部 -->
        <div class="order-header">
          <div class="order-info">
            <span class="order-number">订单号：{{ order.orderNumber }}</span>
            <span class="order-time">{{ formatTime(order.createTime) }}</span>
          </div>
          <div class="order-status">
            <el-tag :type="getStatusType(order.status)" size="large">
              {{ getStatusText(order.status) }}
            </el-tag>
          </div>
        </div>

        <!-- 商家信息 -->
        <div class="merchant-info">
          <el-icon><Shop /></el-icon>
          <span class="merchant-name">{{ order.merchantName || order.merchant?.shopName }}</span>
          <span class="merchant-address">{{ order.merchant?.address }}</span>
        </div>

        <!-- 客户信息 -->
        <div class="customer-info">
          <el-icon><User /></el-icon>
          <span class="customer-name">{{ order.deliveryName }}</span>
          <span class="customer-phone">{{ order.deliveryPhone }}</span>
        </div>

        <!-- 配送信息 -->
        <div class="delivery-info">
          <el-icon><Location /></el-icon>
          <div class="address-info">
            <div class="address">{{ order.deliveryAddress }}</div>
            <div class="distance" v-if="order.distance">距离约 {{ order.distance }}km</div>
          </div>
        </div>

        <!-- 订单商品简介 -->
        <div class="order-summary">
          <div class="items-count">
            共{{ order.items?.length || 0 }}件商品
          </div>
          <div class="order-amount">
            <span class="label">配送费：</span>
            <span class="delivery-fee">¥{{ order.deliveryFee }}</span>
          </div>
        </div>

        <!-- 订单备注 -->
        <div v-if="order.remark" class="order-remark">
          <el-icon><Document /></el-icon>
          <span>备注：{{ order.remark }}</span>
        </div>

        <!-- 订单操作 -->
        <div class="order-actions">
          <el-button 
            v-if="order.status === 'READY'" 
            type="primary" 
            size="small"
            @click="acceptOrder(order)"
            :disabled="!isOnline"
          >
            接单
          </el-button>
          <el-button 
            v-if="order.status === 'DELIVERING' && order.deliveryPersonId === currentUserId" 
            type="success" 
            size="small"
            @click="completeOrder(order)"
          >
            完成配送
          </el-button>
          <el-button 
            size="small" 
            @click="viewOrderDetail(order)"
          >
            查看详情
          </el-button>
          <el-button 
            v-if="order.status === 'DELIVERING' && order.deliveryPersonId === currentUserId" 
            size="small" 
            @click="callCustomer(order)"
          >
            联系客户
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>

    <!-- 空状态 -->
    <el-empty v-if="!loading && orders.length === 0" description="暂无订单">
      <el-button v-if="activeStatus === 'READY'" type="primary" @click="refreshOrders">
        刷新看看
      </el-button>
    </el-empty>

    <!-- 分页 -->
    <div v-if="total > 0" class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 订单详情弹窗 -->
    <el-dialog v-model="detailVisible" title="订单详情" width="600px">
      <div v-if="selectedOrder" class="order-detail">
        <div class="detail-section">
          <h4>订单信息</h4>
          <div class="detail-item">
            <span class="label">订单号：</span>
            <span>{{ selectedOrder.orderNumber }}</span>
          </div>
          <div class="detail-item">
            <span class="label">下单时间：</span>
            <span>{{ formatTime(selectedOrder.createTime) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">订单状态：</span>
            <el-tag :type="getStatusType(selectedOrder.status)">
              {{ getStatusText(selectedOrder.status) }}
            </el-tag>
          </div>
        </div>

        <div class="detail-section">
          <h4>客户信息</h4>
          <div class="detail-item">
            <span class="label">客户姓名：</span>
            <span>{{ selectedOrder.deliveryName }}</span>
          </div>
          <div class="detail-item">
            <span class="label">联系电话：</span>
            <span>{{ selectedOrder.deliveryPhone }}</span>
          </div>
          <div class="detail-item">
            <span class="label">配送地址：</span>
            <span>{{ selectedOrder.deliveryAddress }}</span>
          </div>
        </div>

        <div class="detail-section">
          <h4>商品信息</h4>
          <div class="detail-items">
            <div v-for="item in selectedOrder.items" :key="item.id" class="detail-item-row">
              <span class="item-name">{{ item.itemName }}</span>
              <span class="item-quantity">x{{ item.quantity }}</span>
              <span class="item-price">¥{{ item.totalPrice }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '../../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Refresh, Shop, User, Location, Document 
} from '@element-plus/icons-vue'
import { 
  getDeliveryOrders, 
  getPendingOrders,
  acceptOrder as acceptOrderApi,
  completeDelivery,
  updateDeliveryStatus
} from '../../api/order'
import dayjs from 'dayjs'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const orders = ref([])
const activeStatus = ref('READY')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const detailVisible = ref(false)
const selectedOrder = ref(null)
const isOnline = ref(false)
const todayDeliveries = ref(0)
const todayEarnings = ref(0)

// 计算属性
const currentUserId = computed(() => userStore.userInfo?.id)

// 获取订单列表
const getOrders = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value - 1,
      size: pageSize.value,
      status: activeStatus.value || undefined
    }
    
    let response
    if (activeStatus.value === 'READY') {
      response = await getPendingOrders(params)
    } else {
      response = await getDeliveryOrders(params)
    }
    
    if (response.success) {
      orders.value = response.data.content || []
      total.value = response.data.totalElements || 0
    } else {
      ElMessage.error(response.message || '获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 刷新订单
const refreshOrders = () => {
  currentPage.value = 1
  getOrders()
}

// 状态变更处理
const handleStatusChange = () => {
  currentPage.value = 1
  getOrders()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  getOrders()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  getOrders()
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'READY': 'warning',
    'DELIVERING': 'primary',
    'COMPLETED': 'success',
    'CANCELLED': 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'READY': '待配送',
    'DELIVERING': '配送中',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return textMap[status] || '未知状态'
}

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

// 上线接单
const goOnline = async () => {
  try {
    await updateDeliveryStatus('ONLINE')
    isOnline.value = true
    ElMessage.success('已上线，可以接单了')
    refreshOrders()
  } catch (error) {
    ElMessage.error('上线失败')
  }
}

// 下线休息
const goOffline = async () => {
  try {
    await ElMessageBox.confirm('确认要下线休息吗？', '下线确认', {
      confirmButtonText: '确认下线',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await updateDeliveryStatus('OFFLINE')
    isOnline.value = false
    ElMessage.success('已下线休息')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('下线失败')
    }
  }
}

// 接单
const acceptOrder = async (order) => {
  try {
    await ElMessageBox.confirm('确认接受此订单？', '接单确认', {
      confirmButtonText: '确认接单',
      cancelButtonText: '取消',
      type: 'success'
    })
    
    await acceptOrderApi(order.id)
    ElMessage.success('接单成功，请尽快前往商家取餐')
    refreshOrders()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('接单失败')
    }
  }
}

// 完成配送
const completeOrder = async (order) => {
  try {
    await ElMessageBox.confirm('确认已完成配送？', '完成配送', {
      confirmButtonText: '确认完成',
      cancelButtonText: '取消',
      type: 'success'
    })
    
    await completeDelivery(order.id)
    ElMessage.success('配送完成，辛苦了！')
    todayDeliveries.value++
    todayEarnings.value += parseFloat(order.deliveryFee || 0)
    refreshOrders()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('完成配送失败')
    }
  }
}

// 查看订单详情
const viewOrderDetail = (order) => {
  selectedOrder.value = order
  detailVisible.value = true
}

// 联系客户
const callCustomer = (order) => {
  const phone = order.deliveryPhone
  if (phone) {
    window.location.href = `tel:${phone}`
  } else {
    ElMessage.warning('无法获取客户电话')
  }
}

// 初始化数据
const initData = () => {
  // 模拟今日数据
  todayDeliveries.value = 5
  todayEarnings.value = 25.00
  isOnline.value = true
}

// 页面初始化
onMounted(() => {
  initData()
  getOrders()
})
</script>

<style scoped>
.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.status-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.status-info {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 8px 0;
}

.status-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.status-item .label {
  font-size: var(--font-size-small);
  opacity: 0.9;
}

.status-item .value {
  font-weight: 600;
  font-size: var(--font-size-medium);
}

.orders-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.order-card {
  border: 1px solid var(--border-extra-light);
  border-radius: var(--border-radius-large);
  overflow: hidden;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: var(--bg-page);
  border-bottom: 1px solid var(--border-extra-light);
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.order-number {
  font-weight: 600;
  color: var(--text-primary);
}

.order-time {
  font-size: var(--font-size-small);
  color: var(--text-secondary);
}

.merchant-info,
.customer-info,
.delivery-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  border-bottom: 1px solid var(--border-extra-light);
}

.merchant-name,
.customer-name {
  font-weight: 500;
  color: var(--text-primary);
}

.merchant-address,
.customer-phone {
  color: var(--text-secondary);
  margin-left: auto;
}

.address-info {
  flex: 1;
}

.address {
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: 4px;
}

.distance {
  font-size: var(--font-size-small);
  color: var(--text-secondary);
}

.order-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: var(--bg-page);
}

.items-count {
  color: var(--text-regular);
}

.order-amount {
  display: flex;
  align-items: center;
  gap: 4px;
}

.delivery-fee {
  font-weight: 600;
  color: var(--primary-color);
}

.order-remark {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  background: var(--bg-page);
  border-top: 1px solid var(--border-extra-light);
  font-size: var(--font-size-small);
  color: var(--text-regular);
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding: 16px 20px;
  border-top: 1px solid var(--border-extra-light);
  background: var(--bg-page);
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

.order-detail {
  max-height: 500px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin: 0 0 12px 0;
  font-size: var(--font-size-medium);
  color: var(--text-primary);
}

.detail-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: var(--font-size-small);
}

.detail-item .label {
  color: var(--text-regular);
  width: 80px;
  flex-shrink: 0;
}

.detail-items {
  background: var(--bg-page);
  border-radius: var(--border-radius-base);
  padding: 12px;
}

.detail-item-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid var(--border-extra-light);
}

.detail-item-row:last-child {
  border-bottom: none;
}

@media (max-width: 768px) {
  .status-info {
    flex-direction: column;
    gap: 16px;
  }
  
  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .order-actions {
    flex-wrap: wrap;
  }
  
  .header-actions {
    flex-direction: column;
  }
}
</style>
